package com.yx.musicplayer.util;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.PowerManager;

import com.yx.musicplayer.service.MusicPlayerService;

import java.io.IOException;
import java.lang.ref.WeakReference;

/**
 * Created by yx on 2017/11/6 0006.
 */

public class MusicPlayer implements MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener {
    private final WeakReference<MusicPlayerService> mService;
    private MediaPlayer mCurrentMediaPlayer = new MediaPlayer();
    public MusicPlayer(final MusicPlayerService service) {
        mService = new WeakReference<MusicPlayerService>(service);
        mCurrentMediaPlayer.setWakeMode(mService.get(), PowerManager.PARTIAL_WAKE_LOCK);

    }

    public void setDataSource(final String path) {
        mCurrentMediaPlayer.reset();
        mCurrentMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
            mCurrentMediaPlayer.setDataSource(path);
            mCurrentMediaPlayer.prepareAsync();
            mCurrentMediaPlayer.setOnCompletionListener(this);
            mCurrentMediaPlayer.setOnErrorListener(this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {

    }

    @Override
    public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
        return false;
    }
}
